<template>
  <div  class="wrapper">
    <BreakSpace label="基本信息" :containerStyle="{ marginBottom: '15px' }" />
    <div style="height:300px">
      <FormPanel
        ref="from"
        :list="initForm"
        :cols="3"
        :formType="value.type"
        :labelWidth="120"
        :isSubmitBtn="false"
        :collapse="false"
        @formChange="changeHandle"
      />
    </div>

    <BreakSpace label="配件信息" :containerStyle="{ marginBottom: '15px' }" />
    <FilterTable
      height="auto"
      ref="tablePeij"
      :columns="partColumns"
      :isSelectColumn="isSelectColumn"
      selectionType="single"
      :isMemoryPagination="true"
      :onSyncTableData="syncPjFun"
      :datakey="'records'"
      :isToperInfo="false"
      :onColumnsChange="partColumns => (this.partColumns = partColumns)"
      columnsRef="notification_maintain_info_02"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="openimportPjDialog">导入配件
        </el-button>
      </template>
    </FilterTable>

    <BaseDialog style="min-height: 80vh;" :visible.sync="visibleImportPeij" width="80vw" title="配件导入" destroyOnClose
                :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '50px' }"
    >
      <ExcelImport
        ref="import"
        template-file-name="配件导入模板.xlsx"
        :importRules="importRules"
        :onBeforeDownloadTemp="setParts"
        :onComplete="importComplete"
        @close="visibleImportPeij = false"
      />
    </BaseDialog>

    <BreakSpace label="审核信息" :containerStyle="{ marginBottom: '15px' }" />
    <approveHistory v-model="approvalparams" />

    <div class="dialogBottmView">
      <el-button @click="closeDialog('closeDialog')">关 闭</el-button>
      <el-button :loading="loadingFlag" v-if="this.djzt === 50051006" @click="saveDialog('50051010')" type="primary">审核通过</el-button>
      <el-button :loading="loadingFlag" @click="saveDialog('50051003')" type="primary">审核驳回</el-button>
      <el-button :loading="loadingFlag" @click="saveDialog('50051005')" type="primary">审核拒绝</el-button>
    </div>
  </div>
</template>

<script>
import { getFileGroup } from '@/api/partsmanage/common/file';
import {saveReturnInfo,getPartsByReturnID,imReturnPart} from '@/api/partsmanage/saleReturnManage/index';
import approveHistory from '../../components/approveHistory';
import { phone} from '@/utils/validate'
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import ExcelImport from '@/components/ExcelImport';
export default {
  name: "returnTechReviewInfo",
  mixins: [dictionary],
  props:{
    value: {
      type: Object,
      data: Object,
      required: true
    },
  },
  components:{
    approveHistory,
    ExcelImport
  },
  data() {
    return {
      type: this.value.type,
      initForm : this.initFormFun(),
      partColumns: this.creatHeaderPartRoleColumns(),
      importRules: this.initImportRuleFun(),
      partList: [],
      isSelectColumn: false,
      visibleImportPeij: false,
      initPartData: {},
      visiblePart: false,
      visiblePartOrder: false,
      visiblePartsGroup: false,
      oderseach: false,
      formData:{},
      searchData: {},
      returnID: '',
      saveData: {
        bkpzsl: 0,
        bkztze: 0,
        partList: []
      },
      djzt: null,
      loadingFlag:false,
      approvalparams: {}
    };
  },
  created() {
    this.init(this.value.data)
  },
  methods: {
    init(data) {
      console.info(data)
      if(this.type==='edit'){
        this.returnID = data.id
        var initdata = {
          id: data.id,
          bkthlx: data.bkthlx,
          ownerCode: data.ownerCode
        }
        this.djzt = data.bkxtzt
        getPartsByReturnID(initdata).then(response => {
          var list = response.data
          console.info(list)
          if(response.resultCode === 200){
            this.$nextTick(()=>{
              this.$refs.tablePeij.EXECUTE_INSERT(list)
            })
          }
        })
        this.approvalparams.xtspid = data.id
        this.approvalparams.xtsplx = 'tt_sale_return'
        this.initForm.forEach(x => {
          if (x.fieldName === 'created_at') {
            x.initialValue = moment(data.createdAt).format('YYYY-MM-DD HH:mm:ss');
          } else if (x.fieldName === 'bkthlx'){
            x.initialValue = data[x.fieldName];
            if(data[x.fieldName] === 50041004 || data[x.fieldName] === 50041005){
              this.oderseach = true
            }
          } else {
            x.initialValue = data[x.fieldName];
          }
        });
        getFileGroup({ "xtdjid": this.returnID, "xtfjlx": "5" }).then(response => {
          var fileList = response.data.records
          this.initForm.forEach(x => {
            if (x.fieldName === 'wayFiles') {
              x.initialValue = fileList
            }
          })
        })
      }
    },
    initFormFun(){
      return [
        {
          type: 'INPUT',
          label: '退货单号',
          fieldName: 'bkxtdh',
          disabled: true,
          hidden: this.value.type === 'add'
        },
        {
          type: 'SELECT',
          label: '退货类型',
          fieldName: 'bkthlx',
          placeholder: '请选择',
          clearable: false,
          initialValue: 50041001,
          itemList: this.createDictList('5004'),
          disabled: true
        },
        {
          type: 'INPUT',
          label: '创建日期',
          fieldName: 'created_at',
          placeholder: '请输入',
          initialValue:  moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          disabled: true
        },
        {
          type: 'INPUT',
          label: '经办人',
          fieldName: 'bkjbry',
          placeholder: '请输入',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '经办人电话',
          fieldName: 'bkrydh',
          placeholder: '请输入',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '采购单号',
          fieldName: 'bkysdj',
          disabled: true,
        },
        {
          type: 'TEXT_AREA',
          label: '退货原因',
          fieldName: 'bkxtly',
          disabled: true,
          selfCols:3
        },
        {
          type: 'TEXT_AREA',
          label: '审核意见',
          fieldName: 'xtspnr',
          selfCols:3
        },
        {
          selfCols: 3,
          type: 'UPLOAD_FILE',
          label: '上传文件',
          fieldName: 'wayFiles',
          placeholder: '上传文件...',
          initialValue: '',
          disabled:true,
          upload: {
            actionUrl: '/api/file/oss/upload',
            limit: 1,
            tipText: '（支持：PDF、RAR、JPG格式）'
          }
        }
      ]
    },
    creatHeaderPartRoleColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          fixed: 'left',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        { title: '厂家发货仓库名称', fixed: 'left', dataIndex: 'bsckmc', sorter: true },
        { title: '配件id', dataIndex: 'bjpjid', hidden: true },
        { title: '配件代码', fixed: 'left', dataIndex: 'bjxmbh', sorter: true },
        { title: '配件名称', fixed: 'left', dataIndex: 'bjzwmc', sorter: true },
        // { title: '可退货数量', dataIndex: 'pjktsl', sorter: true },
        // { title: '库存数量', dataIndex: 'pjkykc', sorter: true },
        { title: '采购单价', dataIndex: 'jjhdj', sorter: true },
        { title: '折扣率', dataIndex: 'pjzkl', sorter: true },
        { title: '折扣后单价', dataIndex: 'bsxszk', sorter: true },
        { title: '退货数量', dataIndex: 'bkthsl', sorter: true },
        {
          title: '批准退货数量',
          dataIndex: 'bkshsl',
          filterType: 'input',
          sorter: true,
          editable: true,
          editType: 'number',
          editPattern: /(^[1-9]\d*$)/,
          editValidator:(val, row, callback) => {
            if (Number(val) <= 0) {
              return callback(new Error('批准退货数量需大于0'))
            }
            if (Number(val) > Number(row.bkthsl)) {
            //   if(this.oderseach){ //呆滞件，退网
            //     callback()
            //   } else {
            //     if(Number(val) <= Number(row.bsspsl) ){
            //       callback()
            //     } else {
            //       callback(new Error('退货数量要小于可退数量！'))
            //     }
            //   }
            // } else {
              return callback(new Error('批准退货数量要小于申请数量！'))
            }
            row.bkzonj = Number(row.bsxszk) * Number(row.bkshsl);
            // row.bkzonj = (Number(row.jjhdj) *Number(row.pjzkl) * Number(row.bkshsl)/100).toFixed(2);
          }
        },
        { title: '实际退货数量', dataIndex: 'bksjsl', sorter: true },
        { title: '实际退货金额', dataIndex: 'bkzonj', sorter: true },
        { title: '配件属性', dataIndex: 'bjpjsx', sorter: true, render: props => { return <span>{this.createDictText(props.row.bjpjsx, '5000')}</span>; } },
        { title: '状态',
          editType: 'select',
          dataIndex: 'bkthzt',
          editable: true,
          editItems: [{text: '通过', value: 1 },{text: '拒绝', value: 2 }]
        },
        { title: '拒绝原因', dataIndex: 'bkjjyy', sorter: true, filter: true, filterType: 'input', editable: true }
      ];
    },
    changeHandle(val){
      this.saveData=val
    },
    syncPjFun(details){
      this.formData.details = details
    },
    initImportRuleFun() {
      return [
        // {
        //   prop: 'bsckdm', title: '仓库名称'
        // },
        // {
        //   prop: 'bsckmc', title: '仓库代码'
        // },
        {
          prop: 'bjxmbh', title: '配件代码',
          rule: [
            {required: true, message: '配件代码不能为空'}
          ]
        },
        {
          prop: 'bjzwmc', title: '配件名称'
        },
        // {
        //   prop: 'xsddhm', title: '配件订单号'
        // },
        {
          prop: 'bjpjsx', title: '配件属性',
          rule: [
            {required: true, message: '配件属性不能为空'},
            {itemList: this.createDictList('5000')}
          ]
        },
        {
          prop: 'bkthsl', title: '退货数量'
        },
        {
          prop: 'bkshsl', title: '批准退货数量',
          rule: [
            {required: true, message: '批准退货数量不能为空'},
            {pattern: /(^[1-9]\d*$)/, message: '请填写正确的批准退货数量'}
          ]
        }
      ]
    },
    //保存
    async saveDialog(val) {
      this.$refs.from.SUBMIT_FORM();
      const err1 = this.$refs.tablePeij.GET_REQUIRED_ERROR();
      const err2 = this.$refs.tablePeij.GET_FORMAT_ERROR();
      if(err1|| err2) return;
      console.info(this.saveData)
      if(val=='50051003'|| val=='50051005'){
        if(!this.saveData.xtspnr || typeof(this.saveData.xtspnr)=='undefined' || this.saveData.xtspnr ==''){
          this.$notify.error({title: '提示信息',message:'驳回和拒绝时审核意见必填!'});
          return;
        }
      }
      if (this.saveData) {
        this.saveData.editType = 'review'
        this.saveData.bkxtzt = val
        this.saveData.id = this.returnID
        this.saveData.partList = this.formData.details
        this.loadingFlag = true;
        await this.getTotal()
        let res =await saveReturnInfo(this.saveData)

        if (res.resultCode === 200) {
          this.$notify.success({title: '提示信息',message:'保存成功!'});
          this.loadingFlag = false;
          this.closeDialog('refresh')
        } else {
          this.$notify.error({title: '提示信息',message:res.errMsg||'保存失败!'});
        }
      }
    },
    //取消操作
    closeDialog(type) {
      this.$emit('close', type);
    },
    getTotal(){
      var totalNum = 0
      var totalMoney = 0
      this.saveData.partList.forEach(i => {
        if(i.bkthzt!==2) {
          totalNum = totalNum + Number(i.bkshsl);
          totalMoney = totalMoney + Number(i.bkzonj);
        }
      })
      this.saveData.bkxtze = totalMoney
      this.saveData.bkpzsl = totalNum
      console.info(this.saveData);
    },
    /* 打开导入配件Dialog */
    openimportPjDialog() {
      if (this.validForm()) {
        this.visibleImportPeij = true;
      }
    },
    validForm() {
      var bkthlx;
      this.initForm.forEach(x => {
        if (x.fieldName === 'bkthlx') {
          bkthlx = x.initialValue
        }
      });
      this.searchData =  {
        id: this.returnID,
        bkthlx: bkthlx
      };
      return true;

    },
    setParts(callback) {
      // 查询所有
      this.searchData.type = 'unlimit'
      getPartsByReturnID(this.searchData).then(res => {
        console.info(res.data)
        res.data.forEach(i => {
          i.bjpjsx = this.createDictText(i.bjpjsx, '5000')
        })
        callback(res.data)
      })
    },
    importComplete(datas, callback) {
      console.info(datas);
      var bkthlx;
      this.initForm.forEach(x => {
        if (x.fieldName === 'bkthlx') {
          bkthlx = x.initialValue
        }
      });
      const errorData = []
      datas.forEach((item, index1) => {
        const indexarr = []
        datas.forEach((i, index2) => {
          if (
            i.bjxmbh === item.bjxmbh &&
            i.bjpjsx === item.bjpjsx &&
            index1 !== index2) {
            indexarr.push(index2 + 1)
          }
        })
        if (indexarr.length) {
          errorData.push({
            rownum: index1 + 1,
            errormsg: `配件信息和${indexarr.join(',')}行重复`
          })
        }
      })
      if (errorData.length) {
        callback(errorData)
      }
      else {
        var importData = {
          datas: datas,
          bkthlx: bkthlx,
          type: 'review',
          id: this.returnID
        }
        imReturnPart(importData).then(res => {
          console.info(res)
          if(res.status){
            this.visibleImportPeij = false
            this.$notify.success({title: '提示信息', message: '导入验证成功'});
            this.selectedPartFun(res.data)
            callback()
          }else{
            callback(res.data)
          }
        })
      }
    },
    selectedPartFun(val) {
      console.info(222)
      console.info(val)
      console.info(this.formData.details)
      var list = []
      val.forEach(x => {
        this.formData.details.forEach(item => {
          if (item.bjpjid === x.bjpjid) {
            item.bkshsl = x.bkshsl
            return
          }
        })
      })
      console.info(list)
    }
  }
};
</script>
<style scoped>
.wrapper {
  height: calc(100vh - 110px);
}
</style>
